import { loginApi, logoutApi } from "@/api/auth";
import { getUserInfoApi } from "@/api/user";
import { resetRouter } from "@/router";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";
import { store } from "@/store";

export const useUserStore = defineStore("user", () => {
	const user: UserInfo = {
		roles: [],
		perms: []
	};

	const token = useStorage("accessToken", "");

	/**
	 * 登录
	 * @param loginData
	 * @returns Promise
	 */
	function login(loginData: LoginData) {
		return new Promise<void>((resolve, reject) => {
			loginApi(loginData)
				.then((response) => {
					const { tokenType, accessToken } = response.data;
					token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	}

	/**
	 * 获取信息(用户昵称、头像、角色集合、权限集合)
	 * @return {Promise<UserInfo>}
	 */
	function getUserInfo() {
		return new Promise<UserInfo>((resolve, reject) => {
			getUserInfoApi()
				.then(({ data }) => {
					console.log(data);
					if (!data) {
						reject("Verification failed, please Login again.");
						return;
					}
					if (!data.roles || data.roles.length <= 0) {
						reject("getUserInfo: roles must be a non-null array!");
						return;
					}
					Object.assign(user, { ...data });
					resolve(data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	}

	/**
	 * 退出登录
	 * @returns Promise
	 */
	function logout() {
		return new Promise<void>((resolve, reject) => {
			logoutApi()
				.then(() => {
					token.value = "";
					location.reload(); // 清空路由
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	}

	/**
	 * 移除token
	 * @returns Promise
	 */
	function resetToken() {
		return new Promise<void>((resolve) => {
			token.value = "";
			resetRouter();
			resolve();
		});
	}

	return {
		token,
		user,
		login,
		getUserInfo,
		logout,
		resetToken
	};
});

/**
 * 非setup
 * @returns useUserStore
 * */
export function useUserStoreHook() {
	return useUserStore(store);
}
